<template>
    <div class="context-menu-component menu-container" ref="menuRef">
        <a-menu mode="vertical" style="width: 220px; border: 1px solid #ccc;" :selectable="false">
            <a-menu-item v-for="(action, index) in actions" :key="index" @click="action.action(componentId)">
                <span class="item-text">{{ operationText[action.key].text }}</span>
                <span class="item-shortcut">{{ operationText[action.key].shortcut }}</span>
            </a-menu-item>
        </a-menu>
    </div>
</template>
<script setup lang="ts" name="InputEdit">
import { type PropType, onMounted, onUnmounted, ref } from 'vue'
import { operationText } from '@/plugins/dataOperations'
import { getParentElement} from '@/constant/helper'

// 定义父组件传过来的值
const props = defineProps({
    actions: {
        type: Array as PropType<ActionItem[]>,
        required: true
    },
    triggerClass: {
        type: String,
        default: 'edit-wrapper'
    }
});

const menuRef = ref<HTMLElement | null>(null)
const componentId = ref('')
const triggerContextMenu =(e: MouseEvent)=>{
    //e.preventDefault()
    const domElement = menuRef.value as HTMLElement
    const wrapperElement = getParentElement(e.target as HTMLElement, props.triggerClass)
    if (wrapperElement) {
        domElement.style.display = 'block'
        domElement.style.top = e.pageY + 'px'
        domElement.style.left = e.pageX + 'px'
        const cid = wrapperElement.dataset.componentId
        if (cid) {
            componentId.value = cid
        }
    }
}
const handleClick = () => {
    const domElement = menuRef.value as HTMLElement
    domElement.style.display = 'none'
}
onMounted(() => {
    document.addEventListener('contextmenu', triggerContextMenu)
    document.addEventListener('click', handleClick)
})
onUnmounted(() => {
    document.removeEventListener('contextmenu', triggerContextMenu)
    document.removeEventListener('click', handleClick)
})
</script>
<style>
.menu-container {
    display: none;
    position: absolute;
    background: #fff;
    z-index: 2000;
    cursor: pointer;
}

.menu-container .ant-menu-item {
    display: flex;
    justify-content: space-between;
    
}

.menu-container .ant-menu-item:hover {
    background: #efefef;
}

.ant-menu-item .item-shortcut {
    color: #ccc;
}
</style>